﻿using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace OkTool.Crypto
{
    public class CryptoUtil
    {
        public static string MD5(string str, bool isLower = false)
        {
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str);
            if (isLower)
            {

                return MD5(bytes).ToLower();
            }
            return MD5(bytes);
        }

        public static string MD5(byte[] bytes)
        {
            using (MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] computeBytes = md5.ComputeHash(bytes);
                string result = "";
                for (int i = 0; i < computeBytes.Length; i++)
                {
                    result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
                }
                return result;
            }
        }

        public static string MD5(Stream stream)
        {
            using (MD5 md5 = System.Security.Cryptography.MD5.Create())
            {
                byte[] computeBytes = md5.ComputeHash(stream);
                string result = "";
                for (int i = 0; i < computeBytes.Length; i++)
                {
                    result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X");
                }
                return result;
            }
        }
        public static string SHA1(string content, Encoding encode)
        {
            try
            {
                SHA1 sha1 = new SHA1CryptoServiceProvider();
                byte[] bytes_in = encode.GetBytes(content);
                byte[] bytes_out = sha1.ComputeHash(bytes_in);
                sha1.Dispose();
                StringBuilder ret = new StringBuilder();
                foreach (byte b in bytes_out)
                {
                    //{0:X2} 大写
                    ret.AppendFormat("{0:x2}", b);
                }
                var hex = ret.ToString();
                return hex;
            }
            catch (Exception ex)
            {
                throw new Exception("SHA1加密出错：" + ex.Message);
            }
        }
        public static string Sha1(string data, Encoding encode)
        {
            using (SHA1Managed md = new SHA1Managed())
            {
                byte[] bytes_out = md.ComputeHash(encode.GetBytes(data));
                StringBuilder ret = new StringBuilder();
                foreach (byte b in bytes_out)
                {
                    //{0:X2} 大写
                    ret.AppendFormat("{0:x2}", b);
                }
                var hex = ret.ToString();
                return hex;
            } 
        }
    }
}
